package net.wwang.open.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author WangWei
 * @date 2020/8/11
 */
@Slf4j
public class JsonUtil {

    /**
     * 对象转json
     * @param object
     * @return
     */
    public static Object objectToJsonString(Object object){
        ObjectMapper mapper = new ObjectMapper();
        String jsonString="";
        Object o = null;
        try {
            jsonString=mapper.writeValueAsString(object);
            o = mapper.readValue(jsonString,Object.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return o;
    }

    /**
     * map转json
     * @param map
     * @return
     */
    public static String mapToJsonString(Map map){
        ObjectMapper mapper = new ObjectMapper();
        String jsonString="";
        try {
            jsonString=mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    /**
     * json转map
     * @param jsonStr
     * @return
     */
    public static Map jsonStringToMap(String jsonStr){
        ObjectMapper mapper = new ObjectMapper();
        Map map = null;
        try {
             map = mapper.readValue(jsonStr, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return map;
    }

}
